package flc.ast.activity;

import static java.security.AccessController.getContext;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.king.zxing.util.CodeUtils;
import com.stark.file.transfer.core.TfConst;
import com.stark.file.transfer.core.TransferableSendManager;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.SelectFileBean;
import flc.ast.databinding.ActivityFileSendShowQrBinding;
import flc.ast.dialog.SendProgressDialog;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.BroadcastReceiverUtil;
import stark.common.basic.utils.IOUtil;
import stark.common.basic.utils.RxUtil;

public class FileSendShowQrActivity extends BaseAc<ActivityFileSendShowQrBinding> {

    //是否跳转到发送文件界面的标志
    private boolean hasGoFileSend = false;
    private BroadcastReceiver mNetReceiver;
    private ImageView mQrCodeView;

    @Override
    protected int onCreate() {
        return R.layout.activity_file_send_show_qr;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFileSendBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        ImageView imageView = mDataBinding.ivQrCode;
        mQrCodeView = imageView;

        updateQrView(imageView);
        //注册监听网络状态的广播接收器
        registerNetReceiver();

        //开启服务端，等待客户端扫码并连接
        TransferableSendManager.getInstance().createServerSocket(new TransferableSendManager.IServerCallback() {
            @Override
            public void onFirstClientCome() {
                //客户端扫码并连接了，则跳转到发送界面开始发送文件
//                startActivity(FileSendActivity.class);
                showSendProgressDialog();
//                hasGoFileSend = true;
//                onBackPressed();
            }
        });

        //创建等待客户端连接的任务
        createCheckConnectTask();
    }

    @Override
    protected void initData() {

    }

    private void showSendProgressDialog() {
        SendProgressDialog dialog = new SendProgressDialog(mContext);
        dialog.setListener(new SendProgressDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                hasGoFileSend = true;
                onBackPressed();
                ActivityUtils.finishActivity(FileTransferActivity.class);
            }
        });
        dialog.show();
    }



    /**
     * 注册监听网络状态变化的广播接收器，以自动更新二维码
     */
    private void registerNetReceiver() {
        if (mNetReceiver == null) {
            mNetReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateQrView(mQrCodeView);
                }
            };
            IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            BroadcastReceiverUtil.registerReceiver(mContext, mNetReceiver, filter);
        }
    }


    private ServerSocket mServerSocket;

    /**
     * 创建等待客户端连接的任务以检测客户端是否跟本设备在同一局域网内
     */
    private void createCheckConnectTask() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                try {
                    mServerSocket = new ServerSocket(TfConst.IP_PORT_CHECK_CONNECT);
                    mServerSocket.accept();
                    mServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                emitter.onNext(true);
            }

            @Override
            public void accept(Boolean obj) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!hasGoFileSend) {
            TransferableSendManager.getInstance().clear();
        }
        unregisterNetReceiver();
        destroyCheckConnectTask();
    }


    /**
     * 注销监听网络状态变化的广播接收器
     */
    private void unregisterNetReceiver() {
        if (mNetReceiver != null) {
            unregisterReceiver(mNetReceiver);
            mNetReceiver = null;
        }
    }

    /**
     * 销毁检测任务
     */
    private void destroyCheckConnectTask() {
        IOUtil.close(mServerSocket);
    }

    private void updateQrView(ImageView imageView) {
        int height = SizeUtils.dp2px(300);
        String ip = getIp();
        if (TextUtils.isEmpty(ip)) {
            //无网络时，将无法获取到ip，则设置一个无效的二维码
            ip = TfConst.INVALID_IP;
        }
        Bitmap bitmap = CodeUtils.createQRCode(ip, height);
        imageView.setImageBitmap(bitmap);
    }


    /**
     * 返回当前设备的ip地址
     *
     * @return
     */
    private String getIp() {
        String ip = NetworkUtils.getIPAddress(true);
        ;
        try {
            String wifiIp = NetworkUtils.getIpAddressByWifi();
            //这里添加这样的处理是因为发现有在小米的Android12系统的手机上通过NetworkUtils.getIPAddress无法
            //获取到局域网地址，而是直接获取到公网地址
            if (!TextUtils.isEmpty(wifiIp) && wifiIp.startsWith("192")) {
                return wifiIp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

}